package com.undsf.httpclient

import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import redis.clients.jedis.Jedis

/**
 * Created by Arathi on 2017/8/21.
 */
class CachedHttpClient() {
    val client : OkHttpClient = OkHttpClient.Builder().build()
    var redis : Jedis = Jedis("localhost", 6379)
    var key : String = "pages"

    constructor(redisAddress: String, redisPort: Int, redisKey: String) : this() {
        redis = Jedis(redisAddress, redisPort)
        key = redisKey
    }

    fun get(url: String): String {
        var content: String = ""
        val hit: Boolean = redis.hexists(key, url)

        if (!hit) {
            val request: Request? = Request.Builder().url(url).build()
            val response: Response? = client.newCall(request).execute()
            content = response?.body()?.string() ?: ""
            redis.hset(key, url, content)
        }
        else {
            content = redis.hget(key, url)
        }

        return content
    }

    fun post(url: String, params: Map<String, String>) : String? {
        return ""
    }
}
